import os
import requests
import json
from config import Config

# 浏览器头
headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
           'X-Requested-With': 'XMLHttpRequest',
           'Connection': 'keep-alive',
           'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36'
                         ' (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'}


class YApi(object):
    cookie = None

    def __init__(self):
        self.cookie = self.login_Yapi()

    def login_Yapi(self):
        headers['Content-Type'] = 'application/json;charset=UTF-8'
        data = {'email': '329189987@qq.com', 'password': "13699730738"}
        data = json.dumps(data)
        r = requests.post('https://cgyapi.chungoulife.com/api/user/login', data=data, headers=headers)
        # 将CookieJar转为字典：
        cookiedict = requests.utils.dict_from_cookiejar(r.cookies)
        cookie = '_yapi_uid=%s; _yapi_token=%s' % (cookiedict['_yapi_uid'], cookiedict['_yapi_token'])
        return cookie

    def api_project_list(self):  # 获取api project_id
        headers['Cookie'] = self.cookie
        r = requests.get("https://cgyapi.chungoulife.com/api/project/list?group_id=89&page=1&limit=10", headers=headers)
        resp = r.json()
        project_id_dict = {}
        for i in resp['data']['list']:
            project_id_dict[i['_id']] = i['name']
        print(project_id_dict)
        return project_id_dict

    def white_list(self, project_id):
        white = []
        if project_id == 17:  # 商城接口
            white = ['邀请PK赛', '']
        elif project_id == 19:  # 淘宝联盟
            white = ['', '']
        elif project_id == 71:  # 新版纯购商城App接口
            white = ['购物车', '老服务-商品']
        elif project_id == 89:# 短链接系统
            white = ['公共分类']
        else:
            pass
        return white

    def get_api_detail(self, id):
        headers['Cookie'] = self.cookie
        # 单条api详情
        r = requests.get("https://cgyapi.chungoulife.com/api/interface/get?id=%s" % id, headers=headers)
        resp = r.json()
        # print(resp['data'])
        return resp['data']

    def get_YApi(self, project_id):
        headers['Cookie'] = self.cookie
        r = requests.get("https://cgyapi.chungoulife.com/api/interface/list_menu?project_id=%s" % project_id,
                         headers=headers)
        resp = r.json()
        white = self.white_list(project_id)
        list_menu = []
        for i in resp['data']:
            if i['name'] not in white:
                continue
            apidict = i
            classname = "Id" + str(i['_id'])
            apidict["classname"] = classname
            for j in apidict['list']:
                apidetail = self.get_api_detail(j['_id'])
                j['detail'] = apidetail
            list_menu.append(apidict)
        print(list_menu)
        self.parse_to_api(list_menu, "YApi%s" % project_id)

    def parse_to_api(self, list_menu, filename):
        """
        自动写入生成api文件方便调用
        :param api_dict:
        :param filename:
        :return:
        """
        api_dir = os.path.join(Config.api_dir)
        # 若不存在则创建该目录
        if not os.path.exists(api_dir):
            os.mkdir(api_dir)
        api_file = "{}.py".format(filename)
        with open(os.path.join(api_dir, api_file), "w+", encoding="utf-8") as f:
            # import写入
            for head in Config.api_head:
                if not head.endswith("\n"):
                    head += "\n"
                f.write(head)
            # 换行
            f.write("\n")
            f.write("api_host = Config.API_HOST")
            f.write("\n")
            f.write("headers = Config.headers")
            f.write("\n\n")

            for i in list_menu:

                # 编写测试类
                print(i)
                f.write("\n")
                f.write("class {}:\n".format(i["classname"]))
                f.write("    \"\"\"{}\"\"\"\n".format(i["name"]))

                for api in i.get('list'):

                    # 编写装饰器
                    f.write("    @classmethod\n")

                    # 编写测试类
                    param = ', method, headers1'
                    param1 = []
                    form = api['detail']['req_body_form']
                    if form and api['detail']['req_body_type'] == 'form':
                        for fo in form:
                            if fo['required'] == "0":
                                continue
                            param1.append(fo['name'])
                            param = param + ', ' + fo['name']
                        param = param + ', **kw'
                    elif 'req_body_other' in api['detail'] and 'required' in json.loads(
                            api['detail']['req_body_other']):
                        param1 = json.loads(api['detail']['req_body_other'])['required']
                        param = param + ', ' + ', '.join(param1) + ', **kw'


                    else:
                        param = param + ', **kw'
                    f.write("    def {}(cls{}):  # Author：{}\n".format('_'.join(api['path'].split('/')[2:]), param,
                                                                       api['detail']['username']))
                    # 编写描述
                    f.write("        \"\"\"\n")
                    f.write("        {}\n".format(1))
                    f.write("        :return:\n")
                    f.write("        \"\"\"\n")

                    # 编写headers
                    for n in api['detail']['req_headers']:
                        if n['name'] == 'Content-Type':
                            f.write("        headers['Content-Type'] = headers1['Content-Type']\n")
                        elif n['name'] == 'token':
                            f.write("        headers['access-token'] = headers1['access-token']\n")
                        elif n['name'] == 'access-token':
                            f.write("        headers['access-token'] = headers1['access-token']\n")
                        elif n['name'] == 'Device-Type':
                            f.write("        headers['Device-Type'] = headers1['Device-Type']\n")

                    # 编写data
                    data = '{'
                    f.write("        data = {\n")
                    if param1:
                        for m in param1:
                            f.write("           '{}': {},\n".format(m, m))
                    f.write("        }\n")
                    f.write("        data.update(kw)\n")

                    # 编写path
                    pa = 'data'
                    if api['detail']['method'] == "POST":
                        pa = 'data'
                    elif api['detail']['method'] == "GET":
                        pa = 'params'
                    f.write("        r = requests.request(method, api_host + '{}',"
                            " headers=headers, {}=data)\n".format(api['path'], pa))
                    f.write("        status_code = r.status_code\n")
                    f.write("        resp = r.json()\n")
                    f.write("        print(status_code)\n")
                    f.write("        print(resp)\n")

                    # 编写return
                    f.write("        return status_code, resp\n\n")


if __name__ == '__main__':
    y = YApi()
    # y.api_project_list()
    # y.get_api_detail(13163)
    y.get_YApi(89)

    pass
